﻿using FastReport.Export.Email;
using Kingdee.BOS;
using Kingdee.BOS.Authentication;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using LanDBom.Models;
using LanDBom.Models.Detailed;
using Microsoft.Office.Interop.Excel;
using Microsoft.SqlServer.Server;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.OpenXmlFormats.Dml.Diagram;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using OfficeOpenXml;
using OfficeOpenXml.DataValidation;
using PuppeteerSharp.Media;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Diagnostics.Eventing.Reader;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using System.Windows.Interop;
using static LanDBom.Controllers.HomeController;
using static NPOI.XSSF.UserModel.Helpers.ColumnHelper;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Application = LanDBom.Models.Application;


namespace LanDBom.Controllers
{
    public class ApplicationController : Controller
    {
        Get_CL get_cl = new Get_CL();
        Get_CL_sho GCS = new Get_CL_sho();
        Application application = new Application();
        Find_ShoTJ shoTJ = new Find_ShoTJ();
        LDbaseEntities db = new LDbaseEntities();

        // GET: Application
        public ActionResult Application(int CL_ID = -99, int state = 0, string Name = "", string Shunqi = "", string Named = "", string App_ban = "", int id = 0, string Lj = "", string Nameed = "", string husJI = "", string name = "", int DE_id = -99, string Bianed = "")
        {
            var listarea = get_cl.GetCL_name();
            ViewBag.lsitCL_name = listarea;
            var listsho = GCS.GetCinemaName(CL_ID);
            ViewBag.listsho = listsho;
            ViewBag.ic = db.IndustryCategory.ToList();
            ViewBag.JIliang = db.Freht.ToList();
            ViewBag.ZUI = db.jectsche.OrderBy(s => s.Je_hanghao).ToList();
            ViewBag.Shuai = Lj;
            ViewBag.temp2 = db.buty3.ToList();

            if (App_ban != "" && state == 0)
            {
                int num = db.Applications.Where(x => x.AP_bian == App_ban).FirstOrDefault().App_id;
                Session["appp_id"] = num;
                Session["JKO_ko"] = get_cl.JIDN(App_ban, Nameed);
                Session["name"] = name;
            }
            else
            {
                Session["appp_id"] = id;
                Session["name"] = "";
            }

            var shunji = db.Dengli.Where(s => s.DE_zhuang != "离职").ToList();
            ViewBag.res = shunji;
            if (state == 1)
            {
                try
                {
                    List<Clirntele> cli = db.Clirntele.Where(s => s.CL_name.Contains(Name)).ToList();
                    //
                    //集成查询客户
                    var client = new K3CloudApi();
                    //用于记录结果
                    StringBuilder Info = new StringBuilder();
                    //业务对象标识
                    string formId = "BD_Customer";
                    string fieldKeys = "FName,FADDRESS,FEMail,FNumber,F_SMGS_Combo_hydl,FRECCONDITIONID.FName,F_SMGS_Text_zdkh";//客户 编码 联系电话 邮箱 通讯地址 备注 省份
                    string Filter = "FName like'%" + Name + "%'and FUseOrgId.FNumber='" + Shunqi + "'and FDocumentStatus='C' and FForbidStatus='A'";
                    //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                    var param = new QueryParam()
                    {
                        FormId = formId,
                        FieldKeys = fieldKeys,
                        FilterString = Filter,
                        TopRowCount = 0,
                        StartRow = 0,
                        Limit = 200,
                    };
                    //调用接口
                    var result = client.ExecuteBillQuery(param.ToJson());


                    //返回的数据类型为List<List<object>>，错误的返回结果只有一行数据且IsSuccess为False
                    if (result.Count == 1)
                    {
                        //对返回结果进行解析和校验，这里使用的是JsonPatch
                        var resultJObject = JArray.Parse(JsonConvert.SerializeObject(result[0]));
                        var queryNode = resultJObject.SelectToken("$..IsSuccess");
                        if (queryNode != null)
                        {
                            var isSuccess = queryNode.Value<Boolean>();
                            Info.AppendLine(isSuccess ? "操作成功" : "操作失败");
                        }
                        else
                        {
                            Jichengss(cli, result);
                            Info.AppendLine("操作成功");
                        }
                    }
                    else
                    {
                        Jichengss(cli, result);
                        Info.AppendLine("操作成功");
                    }
                    var list = from s in cli select new { s.CL_name, s.CL_ju, s.CL_sho, s.CL_bian, s.CL_shuo, s.CL_lian };//遍历出自己数据库的数据
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    string jsongStr = JsonConvert.SerializeObject(list, settings);
                    return Content(jsongStr, "application/json");
                }
                catch (Exception ex)
                {
                    var shu = ex.Message;
                    return Json(shu);
                }

            }
            if (state == 2)
            {
                try
                {
                    List<Formation> fom = db.Formation.Where(s => s.FM_bai.Contains(Named)).ToList();

                    DateTime now = DateTime.Now;
                    string currentDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");

                    var list = from s in fom select new { s.FM_name, s.FM_bai, s.FM_long, s.FM_kuan, s.FM_gao, s.FM_ji, s.FM_Zhuang, s.FM_yj, s.FM_ej, s.FM_nyl, s.FM_gg };
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    string jsongStr = JsonConvert.SerializeObject(list, settings);
                    return Content(jsongStr, "application/json");
                }
                catch (Exception ex)
                {
                    string shdunngf = ex.Message;
                    return Json(shdunngf);
                }
            }
            else if (state == 3)
            {
                var list = db.Design.Where(x => x.DE_shen == App_ban).ToList();
                foreach (var item in list)
                {
                    var JNKM = item.De_dizhi.Split('\\');
                    item.DE_wenjain = JNKM[JNKM.Length - 1];
                }
                var tempt = from s in list select new { s.bom_id, s.DE_id, s.De_shijian, s.DE_Slong, s.De_ren, s.De_dizhi, s.DE_lei, s.DE_tuiLei, s.DZ_Fnajm, s.DZ_ShTIme, s.DE_wenjain, HD = s.IndustryCategory == null ? "" : s.IndustryCategory.ic_name, HX = s.IndustrySubcategory == null ? "" : s.IndustrySubcategory.isu_name, s.DE_BB, s.DE_bzw, s.DE_bzpl, s.DE_tzlb, s.DE_TZname, HU = s.BOMini == null ? "" : s.BOMini.BOM2_wuLiu, s.DE_h1_id, s.DE_h2_id };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(tempt, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 4)
            {
                var list = db.BeiZhu.Where(x => x.B_Bian == App_ban).ToList();
                list = list.OrderByDescending(b => b.B_id).ToList();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 5)
            {
                var list = from s in listsho
                           select new { s.CL_sho };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 6)
            {
                var list = db.Formation.Where(x => x.FM_name == App_ban).ToList();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 9)
            {
                List<BOMini> bomin = db.BOMini.Where(a => a.BOM2_bian == App_ban && a.BOM2_chen == "Leve0").ToList();
                var list = from s in bomin select new { s.BOM2_chen, s.BOM2_Guige, s.BOM2_liao, s.BOM2_Lei, s.BOM2_Nian, s.BOM2_Yong, s.BOM2_fenzi, s.BOM2_duan, s.BOM2_wuLiu, s.BOM2_id };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);

                return Content(jsongStr, "application/json");
            }
            else if (state == 10)
            {
                List<IndustrySubcategory> isc = db.IndustrySubcategory.Where(x => x.ic_id == CL_ID).ToList();
                var list = from s in isc select new { s.isu_name, s.isu_id };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 11)
            {
                List<Applications> applications = db.Applications.Where(x => x.App_id == id).ToList();
                var list = from s in applications
                           select new { s.AP_bian, s.App_ju, s.App_Kehu, s.App_qishi, s.App_JTime, s.APP_name, s.APP_Zhong, s.App_dizhi, s.App_mu, s.App_sho, s.App_lei, s.APP_she, s.App_baozhuangwu, s.App_hangda, s.App_hangxiao, s.AP_ren, s.App_fzr, s.App_Jz, s.App_xmzt, s.App_bu };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 12)
            {
                List<BOMini> B = db.BOMini.Where(x => x.BOM2_bian == App_ban).ToList();
                var list = from s in B
                           select new { s.BOM2_liao, s.BOM2_wuLiu, s.BOM2_mioa, s.BOM2_Nian, s.BOM2_Guige, s.BOM2_fenzi, s.BOM2_Yong, s.BOM2_Lei, s.BOM2_Sone, s.BOM2_ST, s.BOM2_chen, s.BOM2_id };
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    Formatting = Formatting.Indented
                };
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 13)
            {
                Design design = db.Design.Where(x => x.DE_id == id).FirstOrDefault();
                db.Design.Remove(design);
                int temp = db.SaveChanges();
                string message = temp > 0 ? "删除成功" : "删除失败";
                return Content(message, "text / plain");

            }
            else if (state == 14)
            {
                var design = db.ShejinBeiZhu.Where(x => x.SJ_Bian == App_ban).ToList();//
                var del = db.Dengli.ToList();
                var sjidn = from a in design
                            join b in del on a.SJR_id equals b.DE_ID into c
                            from f in c.DefaultIfEmpty()
                            select new { f.DE_nae, f.DE_bumeng, a.SJ_BZ, f.DE_phone, a.SJ_JL };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(sjidn, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 15)
            {
                string num = db.Formation.Where(x => x.FM_bai == App_ban).Count().ToString();
                return Content(num);
            }
            else if (state == 16)
            {
                var wl = db.Formation.Where(x => x.FM_bai == Name).ToList();
                var list = from s in wl
                           select new { s.FM_bai, s.FM_bmcl, s.FM_yj, s.FM_ycl, s.FM_ej, s.FM_ms, s.FM_long, s.FM_kuan, s.FM_gao, s.FM_name, s.FM_nyl, s.FM_zx, s.FM_ji, s.FM_Jieti, s.FM_Zhuang };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");

            }
            else if (state == 17)
            {
                var des = db.Design.Where(x => x.DE_id == id).ToList();
                var temp = from a in des
                           select new { a.DE_JDR, a.DE_wenjain };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 7)
            {
                //集成查询客户
                var client = new K3CloudApi();
                //用于记录结果
                StringBuilder Info = new StringBuilder();
                //业务对象标识
                string formId = "ORG_Organizations";
                string fieldKeys = "FNumber,FName";//客户 编码 联系电话 邮箱 通讯地址 备注 省份
                string Filter = "FDocumentStatus ='C'";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                var param = new QueryParam()
                {
                    FormId = formId,
                    FieldKeys = fieldKeys,
                    FilterString = Filter,
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 20,
                };
                //调用接口
                var result = client.ExecuteBillQuery(param.ToJson());
                if (result == null)
                {
                    return Content("获取错误", "application/json");
                }
                else
                {
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    string jsongStr = JsonConvert.SerializeObject(result, settings);
                    return Content(jsongStr, "application/json");
                }
            }
            else if (state == 20)
            {
                var ShuL = int.Parse(husJI.ToString());
                var shu = db.jectsche.FirstOrDefault(d => d.Je_hanghao == ShuL);
                string meassage = "";
                if (shu == null)
                {
                    var JIKNN = new jectsche
                    {
                        Je_hanghao = ShuL,
                    };
                    db.jectsche.Add(JIKNN);
                    int ji = db.SaveChanges();
                    meassage = ji > 0 ? "添加成功" : "添加失败";
                }
                else
                {
                    meassage = "该最小起订量已存在";
                }
                return Content(meassage);
            }
            else if (state == 18)
            {
                string zhuang = "";
                Applications applications = db.Applications.Where(x => x.App_id == id).FirstOrDefault();
                if (applications == null)
                {
                    return Content(zhuang);
                }
                Designdraw des = db.Designdraw.Where(x => x.D_Ton == applications.AP_bian).FirstOrDefault();
                if (applications.App_bu == "1" && des != null)
                {
                    zhuang = "显示";
                }
                return Content(zhuang);
            }
            else if (state == 30)
            {
                //集成查询客户
                var client = new K3CloudApi();
                //用于记录结果
                StringBuilder Info = new StringBuilder();
                //业务对象标识
                string formId = "BD_NEWSTAFF";
                string fieldKeys = "FName";//客户 编码 联系电话 邮箱 通讯地址 备注 省份
                string Filter = "FDept.FName='销售部' and FUseOrgId.FNumber='10.01'and FForbidStatus='A' and FDocumentStatus ='C'";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                var param = new QueryParam()
                {
                    FormId = formId,
                    FieldKeys = fieldKeys,
                    FilterString = Filter,
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 20,
                };
                //调用接口
                var result = client.ExecuteBillQuery(param.ToJson());
                if (result == null)
                {
                    return Content("获取错误", "application/json");
                }
                else
                {
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    string jsongStr = JsonConvert.SerializeObject(result, settings);
                    return Content(jsongStr, "application/json");
                }
            }
            else if (state == 31)
            {
                //删除对应数据

                int Hjg = 0;
                if (DE_id != -99)
                {
                    var shun = db.Design.Where(s => s.DE_id == DE_id).FirstOrDefault();
                    db.Design.Remove(shun);
                    Hjg = db.SaveChanges();
                }
                return Content(Hjg.ToString());
            }
            else if (state == 34)
            {
                var frg = db.Designdraw.FirstOrDefault(s => s.D_Ton == Bianed);
                frg.D_zhuang = "3";
                db.Entry(frg).State = EntityState.Modified;
                int sun = db.SaveChanges();
                return Content(sun.ToString());
            }
            else if (state == 35)
            {
                //集成查询客户
                var client = new K3CloudApi();
                //用于记录结果
                StringBuilder Info = new StringBuilder();
                //业务对象标识
                string formId = "BD_Customer";
                string fieldKeys = "FNAME1";//客户 编码 联系电话 邮箱 通讯地址 备注 省份
                string Filter = "FName like'%" + Name + "%'and FUseOrgId.FNumber='" + Shunqi + "'and FDocumentStatus='C' and FForbidStatus='A'";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                var param = new QueryParam()
                {
                    FormId = formId,
                    FieldKeys = fieldKeys,
                    FilterString = Filter,
                    TopRowCount = 0,
                    StartRow = 0,
                    Limit = 20,
                };
                //调用接口
                var result = client.ExecuteBillQuery(param.ToJson());
                if (result == null)
                {
                    return Content("获取错误", "application/json");
                }
                else
                {
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    string jsongStr = JsonConvert.SerializeObject(result, settings);
                    return Content(jsongStr, "application/json");
                }
            }
            else if (state == 36)
            {
                var listShoTJ = shoTJ.Get_ShoTJ();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(listShoTJ, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
        public ActionResult Application_2(int CL_ID = -99, int state = 0, string Name = "", string Shunqi = "", string Named = "", string App_ban = "", int id = 0, string Lj = "", string Nameed = "", string husJI = "", string name = "")
        {
            var listShoTJ = shoTJ.Get_ShoTJ();
            ViewBag.listShoTJ = listShoTJ;
            var listarea = get_cl.GetCL_name();
            ViewBag.lsitCL_name = listarea;
            var listsho = GCS.GetCinemaName(CL_ID);
            ViewBag.listsho = listsho;
            ViewBag.ic = db.IndustryCategory.ToList();
            ViewBag.JIliang = db.Freht.ToList();
            ViewBag.ZUI = db.jectsche.ToList();
            ViewBag.Shuai = Lj;
            if (Name != "" && state == 0)
            {
                int num = db.Applications.Where(x => x.AP_bian == Name).FirstOrDefault().App_id;
                Session["appp_id"] = num;
                Session["name"] = Name;
            }
            var shunji = db.Dengli.ToList();
            ViewBag.res = shunji;
            if (state == 1)
            {
                Applications appp = db.Applications.Where(x => x.AP_bian == App_ban).FirstOrDefault();
                string bu = appp.App_bu;
                string she = appp.APP_she;
                string zhuang2 = appp.App_zhuang;

                string qiangw = "";
                if (bu == "1")
                {
                    if (zhuang2 == "保存")
                    {
                        qiangw = "继续创建申请单";
                    }
                    else
                    {
                        Designdraw designdraw = db.Designdraw.Where(x => x.D_Ton == App_ban).FirstOrDefault();
                        if (designdraw != null)
                        {
                            if (designdraw.D_zhuang == "2")
                            {
                                qiangw = "前往设计委托分配任务";
                            }
                            else if (designdraw.D_zhuang == "3")
                            {
                                qiangw = "前往设计委托递交设计图";
                            }
                            else if (designdraw.D_zhuang == "4")
                            {
                                qiangw = "前往设计委托审核项目";
                            }
                        }

                    }
                }
                else if (bu == "2")
                {
                    qiangw = "前往BOM重置";
                }
                else if (bu == "3")
                {
                    qiangw = "二者择一";
                }
                else if (bu == "4")
                {
                    var lid = db.BOMini.Where(x => x.BOM2_bian == App_ban && x.BOM2_Lei == "外购").ToList();
                    List<BOMini> list2 = new List<BOMini>();
                    var iindex = 0;
                    foreach (BOMini b in lid)
                    {
                        var jeiji = b.BOM2_BQing;
                        int twwe = lid.Where(x => x.BOM2_BQing != jeiji && x.BOM2_BQing.Contains(jeiji)).Count();
                        if (twwe == 0)
                        {
                            list2.Add(b);
                        }

                    }
                    foreach (BOMini b2 in list2)
                    {
                        if (b2.BOM2_sunhao != "已询价" && b2.BOM2_sunhao != "已核价")
                        {
                            iindex++;
                        }
                    }
                    if (iindex == 0)
                    {
                        qiangw = "前往物料核价";
                    }
                    else
                    {
                        qiangw = "前往工艺配置";
                    }

                }
                else if (bu == "5")
                {
                    shenpingliu shenpingliu = db.shenpingliu.Where(x => x.FJINF == appp.AP_bian && x.FMIao == "核价审批" && x.Fzhuang == "审核中").FirstOrDefault();
                    if (shenpingliu == null)
                    {
                        qiangw = "前往物料核价";
                    }
                    else
                    {
                        if (shenpingliu.FFZ == "通过")
                        {
                            qiangw = "等待业务发展部经理审核";
                        }
                        else
                        {
                            qiangw = "等待采购主管审核";
                        }
                    }
                }
                else if (bu == "6")
                {
                    shenpingliu shenpingliu = db.shenpingliu.Where(x => x.FJINF == appp.AP_bian && x.FMIao == "对外报价" && x.Fzhuang == "审核中").FirstOrDefault();
                    if (shenpingliu == null)
                    {
                        qiangw = "前往对外报价";
                    }
                    else
                    {
                        if (shenpingliu.FFZ != "通过")
                        {
                            qiangw = "等待客户经理审核";
                        }
                    }
                }
                else if (bu == "7")
                {
                    qiangw = "前往报价生成";
                }
                return Content(qiangw);
            }
            else if (state == 2)
            {
                string zhuang = "";
                int number = db.ShejinBeiZhu.Where(x => x.SJ_Bian == App_ban && x.SJR_id == id).Count();
                if (number == 0)
                {
                    zhuang = "不通过";
                }
                else
                {
                    zhuang = "通过";
                }
                return Content(zhuang);
            }
            else if (state == 3)
            {
                string zhuang = "";
                int index = 0;
                var duty = db.duty.Where(x => x.dl_id == id).ToList();
                var lid = db.BOMini.Where(x => x.BOM2_bian == App_ban && x.BOM2_Lei == "外购").ToList();
                List<BOMini> list2 = new List<BOMini>();
                foreach (BOMini b in lid)
                {
                    var jeiji = b.BOM2_BQing;
                    int twwe = lid.Where(x => x.BOM2_BQing != jeiji && x.BOM2_BQing.Contains(jeiji)).Count();
                    if (twwe == 0)
                    {
                        list2.Add(b);
                    }

                }
                foreach (BOMini b in list2)
                {
                    foreach (duty d in duty)
                    {
                        if (b.BOM2_ST == d.du_name)
                        {
                            index++;
                        }
                    }
                }
                if (index != 0)
                {
                    zhuang = "通过";
                }
                return Content(zhuang);
            }
            else if (state == 4)
            {
                string zhuang = "";
                shenpingliu spl = db.shenpingliu.Where(x => x.FJINF == App_ban && x.Fzhuang == "审核中" && x.FMIao == "核价审批").FirstOrDefault();
                if (spl == null)
                {
                    zhuang = "无";
                }
                else
                {
                    if (spl.FFZ != "通过")
                    {
                        zhuang = "等待采购主管审核";
                    }
                    else
                    {
                        zhuang = "等待业务部发展经理审核审核";
                    }
                }
                return Content(zhuang);
            }
            else if (state == 5)
            {
                string zhuang = "";
                shenpingliu spl = db.shenpingliu.Where(x => x.FJINF == App_ban && x.Fzhuang == "审核中" && x.FMIao == "对外报价").FirstOrDefault();
                if (spl == null)
                {
                    zhuang = "无";
                }
                else
                {
                    if (spl.FFZ != "通过")
                    {
                        zhuang = "等待客户经理审核";
                    }
                }
                return Content(zhuang);
            }
            else if (state == 6)
            {
                string zhuang = "";
                var app = db.Applications.Where(x => x.AP_bian == Name).FirstOrDefault();
                if (app != null)
                {
                    zhuang = app.APP_she;
                }
                return Content(zhuang);
            }
            return View();
        }
        public ActionResult Application_3(int CL_ID = -99, int state = 0, string Name = "", string Shunqi = "", string Named = "", string App_ban = "", int id = 0, string Lj = "", string Nameed = "", string husJI = "", string name = "")
        {
            var listShoTJ = shoTJ.Get_ShoTJ();
            ViewBag.listShoTJ = listShoTJ;
            var listarea = get_cl.GetCL_name();
            ViewBag.lsitCL_name = listarea;
            var listsho = GCS.GetCinemaName(CL_ID);
            ViewBag.listsho = listsho;
            ViewBag.ic = db.IndustryCategory.ToList();
            ViewBag.JIliang = db.Freht.ToList();
            ViewBag.ZUI = db.jectsche.ToList();
            ViewBag.Shuai = Lj;
            if (Name != "" && state == 0)
            {
                int num = db.Applications.Where(x => x.AP_bian == Name).FirstOrDefault().App_id;
                Session["appp_id"] = num;
                Session["name"] = Name;
            }
            var shunji = db.Dengli.ToList();
            ViewBag.res = shunji;
            if (state == 1)
            {
                Applications appp = db.Applications.Where(x => x.AP_bian == App_ban).FirstOrDefault();
                string bu = appp.App_bu;
                string she = appp.APP_she;
                string zhuang2 = appp.App_zhuang;

                string qiangw = "";
                if (bu == "1")
                {
                    if (zhuang2 == "保存")
                    {
                        qiangw = "继续创建申请单";
                    }
                    else
                    {
                        Designdraw designdraw = db.Designdraw.Where(x => x.D_Ton == App_ban).FirstOrDefault();
                        if (designdraw != null)
                        {
                            if (designdraw.D_zhuang == "2")
                            {
                                qiangw = "前往设计委托分配任务";
                            }
                            else if (designdraw.D_zhuang == "3")
                            {
                                qiangw = "前往设计委托递交设计图";
                            }
                            else if (designdraw.D_zhuang == "4")
                            {
                                qiangw = "前往设计委托审核项目";
                            }
                        }

                    }
                }
                else if (bu == "2")
                {
                    qiangw = "前往BOM重置";
                }
                else if (bu == "3")
                {
                    qiangw = "二者择一";
                }
                else if (bu == "4")
                {
                    var lid = db.BOMini.Where(x => x.BOM2_bian == App_ban && x.BOM2_Lei == "外购").ToList();
                    List<BOMini> list2 = new List<BOMini>();
                    var iindex = 0;
                    foreach (BOMini b in lid)
                    {
                        var jeiji = b.BOM2_BQing;
                        int twwe = lid.Where(x => x.BOM2_BQing != jeiji && x.BOM2_BQing.Contains(jeiji)).Count();
                        if (twwe == 0)
                        {
                            list2.Add(b);
                        }

                    }
                    foreach (BOMini b2 in list2)
                    {
                        if (b2.BOM2_sunhao != "已询价" && b2.BOM2_sunhao != "已核价")
                        {
                            iindex++;
                        }
                    }
                    if (iindex == 0)
                    {
                        qiangw = "前往物料核价";
                    }
                    else
                    {
                        qiangw = "前往工艺配置";
                    }

                }
                else if (bu == "5")
                {
                    shenpingliu shenpingliu = db.shenpingliu.Where(x => x.FJINF == appp.AP_bian && x.FMIao == "核价审批" && x.Fzhuang == "审核中").FirstOrDefault();
                    if (shenpingliu == null)
                    {
                        qiangw = "前往物料核价";
                    }
                    else
                    {
                        if (shenpingliu.FFZ == "通过")
                        {
                            qiangw = "等待业务发展部经理审核";
                        }
                        else
                        {
                            qiangw = "等待采购主管审核";
                        }
                    }
                }
                else if (bu == "6")
                {
                    shenpingliu shenpingliu = db.shenpingliu.Where(x => x.FJINF == appp.AP_bian && x.FMIao == "对外报价" && x.Fzhuang == "审核中").FirstOrDefault();
                    if (shenpingliu == null)
                    {
                        qiangw = "前往对外报价";
                    }
                    else
                    {
                        if (shenpingliu.FFZ != "通过")
                        {
                            qiangw = "等待客户经理审核";
                        }
                    }
                }
                else if (bu == "7")
                {
                    qiangw = "前往报价生成";
                }
                return Content(qiangw);
            }
            else if (state == 2)
            {
                string zhuang = "";
                int number = db.ShejinBeiZhu.Where(x => x.SJ_Bian == App_ban && x.SJR_id == id).Count();
                if (number == 0)
                {
                    zhuang = "不通过";
                }
                else
                {
                    zhuang = "通过";
                }
                return Content(zhuang);
            }
            else if (state == 3)
            {
                string zhuang = "";
                int index = 0;
                var duty = db.duty.Where(x => x.dl_id == id).ToList();
                var lid = db.BOMini.Where(x => x.BOM2_bian == App_ban && x.BOM2_Lei == "外购").ToList();
                List<BOMini> list2 = new List<BOMini>();
                foreach (BOMini b in lid)
                {
                    var jeiji = b.BOM2_BQing;
                    int twwe = lid.Where(x => x.BOM2_BQing != jeiji && x.BOM2_BQing.Contains(jeiji)).Count();
                    if (twwe == 0)
                    {
                        list2.Add(b);
                    }

                }
                foreach (BOMini b in list2)
                {
                    foreach (duty d in duty)
                    {
                        if (b.BOM2_ST == d.du_name)
                        {
                            index++;
                        }
                    }
                }
                if (index != 0)
                {
                    zhuang = "通过";
                }
                return Content(zhuang);
            }
            else if (state == 4)
            {
                string zhuang = "";
                shenpingliu spl = db.shenpingliu.Where(x => x.FJINF == App_ban && x.Fzhuang == "审核中" && x.FMIao == "核价审批").FirstOrDefault();
                if (spl == null)
                {
                    zhuang = "无";
                }
                else
                {
                    if (spl.FFZ != "通过")
                    {
                        zhuang = "等待采购主管审核";
                    }
                    else
                    {
                        zhuang = "等待业务部发展经理审核审核";
                    }
                }
                return Content(zhuang);
            }
            else if (state == 5)
            {
                string zhuang = "";
                shenpingliu spl = db.shenpingliu.Where(x => x.FJINF == App_ban && x.Fzhuang == "审核中" && x.FMIao == "对外报价").FirstOrDefault();
                if (spl == null)
                {
                    zhuang = "无";
                }
                else
                {
                    if (spl.FFZ != "通过")
                    {
                        zhuang = "等待客户经理审核";
                    }
                }
                return Content(zhuang);
            }
            else if (state == 6)
            {
                string zhuang = "";
                var app = db.Applications.Where(x => x.AP_bian == Name).FirstOrDefault();
                if (app != null)
                {
                    zhuang = app.APP_she;
                }
                return Content(zhuang);
            }
            return View();
        }

        public ActionResult AppOld_New(int CL_ID = -99, int state = 0, string Name = "", string Shunqi = "", string Named = "", string App_ban = "", int id = 0, string Lj = "", string Nameed = "", string husJI = "", string name = "")
        {
            var listShoTJ = shoTJ.Get_ShoTJ();
            ViewBag.listShoTJ = listShoTJ;
            var listarea = get_cl.GetCL_name();
            ViewBag.lsitCL_name = listarea;
            var listsho = GCS.GetCinemaName(CL_ID);
            ViewBag.listsho = listsho;
            ViewBag.ic = db.IndustryCategory.ToList();
            ViewBag.JIliang = db.Freht.ToList();
            ViewBag.ZUI = db.jectsche.ToList();
            ViewBag.Shuai = Lj;
            if (Name != "" && state == 0)
            {
                int num = db.Applications.Where(x => x.AP_bian == Name).FirstOrDefault().App_id;
                Session["appp_id"] = num;
                Session["name"] = Name;
            }
            var shunji = db.Dengli.ToList();
            ViewBag.res = shunji;
            return View();
        }
        //集成客户  过滤重复的客户名称
        public static void Jichengss(List<Clirntele> cli, List<List<object>> result)
        {
            for (int i = 0; i < result.Count; i++)
            {
                var id = result[i][0].ToString();//客户名称
                var CLsji = cli.Where(s => s.CL_name.Contains(id)).ToList();
                if (CLsji.Count() > 0)
                {
                    foreach (var cl in CLsji)
                    {
                        cl.CL_name = (string)result[i][0];
                        cl.CL_shuo = (string)result[i][4];
                        cl.CL_bian = (string)result[i][3];
                        cl.CL_lian = (string)result[i][5];
                        cl.CL_ZDKH = (string)result[i][6];
                    }
                    continue;
                }
                var ghjk = new Clirntele()
                {
                    CL_name = (string)result[i][0],
                    CL_sho = (string)result[i][1],
                    CL_you = (string)result[i][2],
                    CL_bian = (string)result[i][3],
                    CL_shuo = (string)result[i][4],
                    CL_lian = (string)result[i][5],
                    CL_ZDKH = (string)result[i][6],
                };
                cli.Add(ghjk);
            }
        }

        //public void eDataTypeOn()
        //{
        //    string jfjf = "";
        //    var shugn = (string)result[i][2];
        //    string input = shugn;
        //    // 去除末尾的"MM"（如果它总是存在且你想移除它）  
        //    if (input.EndsWith("MM") || input.EndsWith("mm"))
        //    {
        //        input = input.Substring(0, input.Length - 2);
        //    }

        //    // 定义正则表达式来匹配数字（可能包含小数点）  
        //    string pattern = @"\b\d+(\.\d+)?\b";

        //    // 使用Regex.Matches来找到所有匹配项  
        //    MatchCollection matches = Regex.Matches(input, pattern);

        //    // 遍历匹配项并打印  
        //    foreach (System.Text.RegularExpressions.Match match in matches)
        //    {
        //        if (jfjf == "")
        //        {
        //            jfjf += match.Value;
        //        }
        //        else
        //        {
        //            jfjf += "*" + match.Value;
        //        }
        //    }
        //}



        //集成物料
        public static void Jichewuliao(List<Formation> cli, List<List<object>> result)
        {
            LDbaseEntities lDbase = new LDbaseEntities();
            for (int i = 0; i < result.Count; i++)
            {
                var zzbds = new Regex(@"\d+(\.\d+)? *\*\d+(\.\d+)? *\*\d+(\.\d+)?");
                var zzbdsed = new Regex(@"\d+(\.\d+)? *\*\d+(\.\d+)?");
                var shugn = (string)result[i][2];
                var Fenjie = zzbds.Match(shugn);
                if (Fenjie.Value == "")
                {
                    Fenjie = zzbdsed.Match(shugn);
                    if (Fenjie.Value == "")
                    {
                        Fenjie = zzbds.Match("0*0*0");
                    }
                }

                var Guiges = Fenjie.Value.Split('*');
                double[] doubles = Guiges[0] == "" ? null : Array.ConvertAll(Guiges, s => double.Parse(s));
                var Zhuang = Hdigndd(result, i);
                ///查找物料分类
                var original = (string)result[i][6];//编码
                var Fenl = lDbase.buty2.Where(s => s.ERP_Bm == original || s.ERP_id == original).ToList();//--查询的结果
                var ZLid = 0;
                foreach (var item in Fenl)
                {
                    ZLid = (int)item.zl2_id;
                }
                var shun = Fenl.Count() == 0 ? null : lDbase.buty3.Where(s => s.zl2_id == ZLid).FirstOrDefault().zl2_name;//一级物料

                ///jjj
                var BianM = result[i][0].ToString();
                //取消验证物料唯一
                var shunko = lDbase.Formation.Where(s => s.FM_bai == BianM).FirstOrDefault();
                if (shunko == null)
                {
                    var ghjk = new Formation()
                    {
                        FM_bai = (string)result[i][0],
                        FM_name = (string)result[i][1],
                        FM_gg = Fenjie.ToString(),
                        FM_ej = (string)result[i][7],
                        FM_yj = shun,
                        FM_long = Guiges.Length > 1 ? (decimal?)doubles[0] : null,
                        FM_kuan = Guiges.Length > 1 ? (decimal?)doubles[1] : null,
                        FM_gao = Guiges.Length > 2 ? (decimal?)doubles[2] : null,
                        FM_ji = (string)result[i][4],
                        FM_Zhuang = Zhuang,
                        ERP_id = result[i][8].ToString(),
                    };
                    cli.Add(ghjk);
                }
                else
                {
                    cli.Clear();
                    break;
                }
            }
        }
        //集成供应商
        public static void JicheGong(List<Providers> cli, List<List<object>> result)
        {
            for (int i = 0; i < result.Count; i++)
            {
                var ghjk = new Providers()
                {
                    PR_bian = (string)result[i][0],
                    PR_name = (string)result[i][1]
                };
                cli.Add(ghjk);
            }
        }

        private static string Hdigndd(List<List<object>> result, int i)
        {
            var shun = "";
            int shngsn = int.Parse(result[i][3].ToString());
            switch (shngsn)
            {
                case 1:
                    shun = "外购";
                    break;
                case 2:
                    shun = "自制";
                    break;
                case 3:
                    shun = "委外";
                    break;
                case 4:
                    shun = "特征";
                    break;
                case 5:
                    shun = "虚拟";
                    break;
                case 6:
                    shun = "服务";
                    break;
                case 7:
                    shun = "一次性";
                    break;
                case 9:
                    shun = "配置";
                    break;
                case 10:
                    shun = "资产";
                    break;
                case 11:
                    shun = "费用";
                    break;
                case 12:
                    shun = "模型";
                    break;
                case 13:
                    shun = "产品系列";
                    break;
                default:
                    break;
            }
            return shun;
        }

        public ActionResult AddApplication(Applications applications)
        {
            var bian = applications.AP_bian;
            int index = db.Applications.Where(x => x.AP_bian == bian).Count();
            if (index == 0)
            {
                int rows = application.AddApplication(applications);
                string message = rows > 0 ? "添加成功" : "添加失败";
                return Content(message, "text / plain");
            }
            if (index != 0)
            {
                Applications temp = db.Applications.Where(x => x.AP_bian == bian).FirstOrDefault();
                if (applications.APP_she == "N")
                {
                    Designdraw designdraw = db.Designdraw.Where(x => x.D_Ton == applications.AP_bian).FirstOrDefault();
                    if (designdraw != null)
                    {
                        db.Designdraw.Remove(designdraw);
                        db.SaveChanges();
                    }
                }
                if (applications.App_xmzt == temp.App_xmzt)
                {
                    //Y:是修改  X:是提交
                    if (applications.APP_Zhong == "Y")
                    {
                        applications.App_bu = temp.App_bu;
                    }
                }
                else
                {
                    //项目状态改变
                    if (applications.App_xmzt == "LOST Opportunities" && temp.App_xmzt != "LOST Opportunities")
                    {
                        temp.App_JL = temp.App_bu;
                        temp.App_bu = "-99";
                    }
                    if (applications.App_xmzt == "WON Opportunities" && temp.App_xmzt != "WON Opportunities")
                    {
                        if (temp.App_bu == "-99")
                        {
                            applications.App_bu = temp.App_JL;
                            temp.App_JL = null;
                        }
                    }
                    if (applications.App_xmzt == "OPEN Opportunities" && temp.App_xmzt != "OPEN Opportunities")
                    {
                        if (temp.App_bu == "-99")
                        {
                            applications.App_bu = temp.App_JL;
                            temp.App_JL = null;
                        }
                    }
                }
                if (applications.App_bu == null)
                {
                    applications.App_bu = temp.App_bu;
                }
                if (applications.App_bei == null)
                {
                    applications.App_bei = temp.App_bei;
                }
                if (applications.APP_she == null)
                {
                    applications.APP_she = temp.APP_she;
                }
                if (applications.App_miao == null)
                {
                    applications.App_miao = temp.App_miao;
                }
                applications.App_BanB = applications.App_BanB == null ? temp.App_BanB : applications.App_BanB;
                temp.App_Kehu = applications.App_Kehu;
                temp.AP_ren = applications.AP_ren;
                temp.App_qishi = applications.App_qishi;
                temp.App_JTime = applications.App_JTime;
                temp.APP_name = applications.APP_name;
                temp.APP_Zhong = applications.APP_Zhong;
                temp.App_dizhi = applications.App_dizhi;
                temp.App_ju = applications.App_ju;
                temp.App_mu = applications.App_mu;
                temp.App_sho = applications.App_sho;
                temp.App_lei = applications.App_lei;
                temp.App_tuzhi = applications.App_tuzhi;
                temp.APP_fenL = applications.APP_fenL;
                temp.APP_she = applications.APP_she;
                temp.App_miao = applications.App_miao;
                temp.App_BanB = applications.App_BanB;
                temp.App_zhand = applications.App_zhand;
                temp.App_baozhuangwu = applications.App_baozhuangwu;
                temp.App_hangda = applications.App_hangda;
                temp.App_hangxiao = applications.App_hangxiao;
                temp.App_zhuang = null;
                temp.App_Jz = applications.App_Jz;
                temp.App_fzr = applications.App_fzr;
                temp.App_bu = applications.App_bu;
                temp.App_xmzt = applications.App_xmzt;
                temp.App_bei = applications.App_bei;
                db.Entry(temp).State = EntityState.Modified;
                int num = db.SaveChanges();
                string message = num > 0 ? "提交成功" : "提交失败";
                return Content(message, "text / plain");
            }
            return View();
        }
        public ActionResult Addfor(Formation applications, string names = "")
        {
            string message = "";
            try
            {
                int rows = 0;
                var forme = applications.FM_bai;
                var hunn = db.Formation.Where(s => s.FM_bai == forme).FirstOrDefault();

                if (hunn == null)
                {
                    db.Formation.Add(applications);
                    rows = db.SaveChanges();
                }
                else
                {
                    hunn.FM_name = applications.FM_name;
                    hunn.FM_long = applications.FM_long;
                    hunn.FM_kuan = applications.FM_kuan;
                    hunn.FM_gao = applications.FM_gao;
                    hunn.FM_ji = applications.FM_ji;
                    hunn.FM_kong = applications.FM_kong;
                    hunn.FM_gg = applications.FM_gg;
                    hunn.FM_nyl = applications.FM_nyl;
                    hunn.FM_yj = applications.FM_yj;
                    hunn.FM_bmcl = applications.FM_bmcl;
                    hunn.FM_ycl = applications.FM_ycl;
                    hunn.FM_ms = applications.FM_ms;
                    hunn.FM_zx = applications.FM_zx;
                    hunn.FM_ej = applications.FM_ej;
                    hunn.FM_Jieti = applications.FM_Jieti;
                    db.Entry(hunn).State = EntityState.Modified;
                    rows = db.SaveChanges();//修改物料库数据
                    if (rows > 0)
                    {
                        var Sone = applications.FM_yj;
                        Sone = Sone == "纸质" ? "1" : Sone == "木质" ? "2" : Sone == "塑料" ? "3" : Sone == "金属制品" ? "4" : Sone == "布" ? "5" : Sone == "胶粘制品" ? "6" : Sone == "其他" ? "7" : Sone == "套件" ? "8" : Sone;
                        var bomin = db.BOMini.Where(s => s.BOM2_bian == names && s.BOM2_liao == forme).FirstOrDefault();
                        var JINGK = bomin == null ? -99 : bomin.BOM2_Gong;
                        if (bomin == null)
                        {
                            var messsagede = "修改成功";
                            return Content(messsagede, "text / plain");
                        }
                        bomin.BOM2_Guige = applications.FM_gg;
                        bomin.BOM2_Lei = applications.FM_Zhuang;
                        bomin.BOM2_fenzi = applications.FM_ji;
                        bomin.BOM2_ST = applications.FM_ej;
                        bomin.BOM2_Sone = Sone;
                        bomin.BOM2_GY = null;
                        bomin.BOM2_sunhao = null;
                        bomin.BOM2_Gong = null;
                        bomin.BOM2_Nian = applications.FM_nyl;
                        db.Entry(bomin).State = EntityState.Modified;
                        rows = db.SaveChanges();//修改物料库数据
                        if (rows > 0)
                        {
                            if (JINGK == -99 || JINGK == null)
                            {
                                rows = 1;
                            }
                            else
                            {
                                var OP = db.operational.Where(s => s.OP_ID == JINGK).FirstOrDefault();
                                db.operational.Remove(OP);
                                rows = db.SaveChanges();//修改物料库数据
                                var OPED = db.Ndardo.Where(s => s.Fo_id == applications.FM_bai).FirstOrDefault();
                                if (OPED != null)
                                {
                                    db.Ndardo.Remove(OPED);
                                    rows = db.SaveChanges();//修改物料库数据
                                }
                            }
                        }
                    }
                    var messagede = rows > 0 ? "修改成功" : "修改失败";
                    return Content(messagede, "text / plain");
                    message = rows > 0 ? "添加成功" : "添加失败";
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return Content(message, "text / plain");
        }
        [HttpPost]
        public ActionResult RemoveMaterial(List<Formation> formation)
        {
            if (true)
            {
                int rows = 0;
                foreach (var f in formation)
                {
                    var bian = int.Parse(f.FM_bai);
                    var shuj = db.BOMini.Where(s => s.BOM2_id == bian).FirstOrDefault();
                    var id = shuj.BOM2_liao;
                    db.BOMini.Remove(shuj);
                    rows += db.SaveChanges();
                    var temp = db.Formation.Where(x => x.FM_bai == id).FirstOrDefault();
                    if (temp != null)
                    {
                        db.Formation.Remove(temp);
                        db.SaveChanges();
                    }
                }
                string messaage = "删除" + rows + "条";
                return Json(messaage);
            }
            return View();
        }
        public ActionResult Mormation(Clirntele dl)
        {
            var shunf = db.Clirntele.FirstOrDefault(s => s.CL_ID == dl.CL_ID);
            string message = "";
            if (shunf != null)
            {
                shunf.CL_bian = dl.CL_bian;
                shunf.CL_name = dl.CL_name;
                shunf.CL_di = dl.CL_di;
                shunf.CL_lian = dl.CL_lian;
                shunf.CL_you = dl.CL_you;
                shunf.CL_bei = dl.CL_bei;
                shunf.CL_sho = dl.CL_sho;
                shunf.CL_ju = dl.CL_ju;
                shunf.CL_Huobi = dl.CL_Huobi;
                shunf.CL_Jian = dl.CL_Jian;
                shunf.CL_zhu = dl.CL_zhu;
                shunf.CL_shuo = dl.CL_shuo;
                shunf.CL_Nation = dl.CL_Nation;
                shunf.CL_City = dl.CL_City;
                shunf.CL_District = dl.CL_District;
                db.Entry(shunf).State = EntityState.Modified;
                int shuned = db.SaveChanges();
                message = shuned > 0 ? "修改成功" : "修改失败";
                return Content(message);
            }
            return View();
        }
        public ActionResult Cliview(string KHname, string KHPhone, string Bian = "", int stents = 0, string shund = "")
        {
            var Jins = shund == "" ? 0 : int.Parse(shund);
            List<Clirntele> clirnteles = db.Clirntele.ToList();
            if (KHname != null)
            {
                clirnteles = clirnteles.Where(s => s.CL_name.Contains(KHname)).ToList();
            }
            if (KHPhone != null)
            {
                clirnteles = clirnteles.Where(s => s.CL_lian.Contains(KHPhone)).ToList();
            }
            var tes = clirnteles.Count();//行数
            var yeshu = Math.Ceiling((double)tes / 10);//页数
            ViewBag.Yeshu = tes;
            ViewBag.Shund = yeshu;

            clirnteles = clirnteles.Skip(Jins * 10).Take(10).ToList();//展示页数
            if (stents == 1)
            {
                var shudnmkos = int.Parse(Bian);
                var plpkok = db.Clirntele.FirstOrDefault(s => s.CL_ID == shudnmkos);
                db.Clirntele.Remove(plpkok);
                int sungko = db.SaveChanges();
                string messs = sungko > 0 ? "删除成功" : "删除失败";
                return Content(messs);
            }
            if (stents == 2)
            {
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(clirnteles, settings);
                return Content(jsongStr, "application/json");
            }
            //分页查询
            return View(clirnteles);
        }
        //添加BOM或物料信息s
        [HttpPost]
        public JsonResult AddAppli(List<BOMini> bOMinis)
        {
            //二级标识
            string[] letter = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A1", "B1", "C1", "D1", "E1", "F1", "G1", "H1", "I1", "J1", "K1", "L1", "M1", "N1", "O1", "P1", "Q1", "R1", "S1", "T1", "U1", "V1", "W1", "X1", "Y1", "Z1", "A2", "B2", "C2", "D2", "E2", "F2", "G2", "H2", "I2", "J2", "K2", "L2", "M2", "N2", "O2", "P2", "Q2", "R2", "S2", "T2", "U2", "V2", "W2", "X2", "Y2", "Z2" };
            if (bOMinis == null)
            {
                bOMinis = new List<BOMini>();
            }
            var st = 0;
            var hdfu = "";
            for (int i = 0; i < bOMinis.Count; i++)
            {
                if (bOMinis[i].BOM2_chen == "Leve0")
                {
                    var aed = bOMinis[i].BOM2_bian;
                    var vf = bOMinis[i].BOM2_wuLiu;
                    hdfu = bOMinis[i].BOM2_BQing;
                    bOMinis[i].BOM2_BQing = hdfu;
                }
                if (bOMinis[i].BOM2_chen == "leve1")
                {
                    bOMinis[i].BOM2_BQing = hdfu + "-" + letter[st].ToString();
                    st++;
                }
                if (bOMinis[i].BOM2_chen == "leve2")
                {
                    if (bOMinis[i - 1].BOM2_chen == "leve1")
                    {
                        bOMinis[i].BOM2_BQing = bOMinis[i - 1].BOM2_BQing + "-a";
                    }
                    if (bOMinis[i - 1].BOM2_chen == "leve2")
                    {
                        bOMinis[i].BOM2_BQing = bOMinis[i - 1].BOM2_BQing;
                    }
                }
            }
            foreach (BOMini b in bOMinis)
            {
                //取banb
                var shifn = b.BOM2_bian;
                var app = db.Applications.FirstOrDefault(s => s.AP_bian == shifn);
                int wuliao = (from s in db.Formation where s.FM_name == b.BOM2_wuLiu select s.FM_ID).FirstOrDefault();/*获取formationde id 信息*/
                var appid = db.Formation.Where(s => s.FM_ID == wuliao).FirstOrDefault();/*获取formationde 料号信息*/
                var BOminde = b.BOM2_bian;
                var app_bom = db.Applications.FirstOrDefault(s => s.AP_bian == BOminde);
                //进行赋值 添加id的值
                b.Fo_id = null;
                if (wuliao > 0)
                {
                    b.Fo_id = wuliao;
                }
                b.BOM2_Zhuang = app.App_BanB;
                var hunji = b.BOM2_BQing;
                var A = b.BOM2_bian;
                var h = db.BOMini.Where(s => s.BOM2_BQing == hunji && s.BOM2_bian == A).FirstOrDefault();///判断该条是否存在
                if (h != null)
                {
                    h.BOM2_wuLiu = b.BOM2_wuLiu;
                    h.BOM2_liao = b.BOM2_liao;
                    h.BOM2_duan = b.BOM2_duan;
                    h.BOM2_Guige = b.BOM2_Guige;
                    h.BOM2_Nian = b.BOM2_Nian;
                    h.BOM2_Yong = b.BOM2_Yong;
                    h.BOM2_fenzi = b.BOM2_fenzi;
                    h.BOM2_Lei = b.BOM2_Lei;
                    h.BOM2_Sone = b.BOM2_Sone;
                    h.BOM2_ST = b.BOM2_ST;
                    db.Entry(h).State = EntityState.Modified;
                }
                else
                {
                    db.BOMini.Add(b);
                }
            }
            int sun = db.SaveChanges();
            return Json(sun);
        }
        find_appliction FA = new find_appliction();
        public ActionResult Requisition(int state = 0, string BB_SQ_xmmc = null, string BB_SQ_khmc = null, string BB_SQ_sqrq = null, string BB_SQ_gjz = null, string jssj = null, string qssj = null, string danhao = null, string xmlx = null, string jzrq = null)
        {
            if (state == 1)
            {
                var listapp = FA.find_Contracts(BB_SQ_xmmc, BB_SQ_khmc, BB_SQ_gjz, jssj, qssj, danhao, xmlx, jzrq);
                var temp = from a in listapp
                           select new { a.AP_bian, a.App_Kehu, a.APP_name, a.App_qishi, a.App_JTime, a.App_dizhi, a.APP_Zhong, a.App_mu, a.App_lei, a.App_sho, APP_she = a.APP_she == "S" ? "Y" : a.APP_she, a.App_BanB, a.App_bu, a.App_zhuang, a.APP_shr, a.APP_liy, a.AP_ren, a.App_id };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(listapp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 2)
            {
                var listapp = FA.find_DHLY(BB_SQ_xmmc);
                var temp = from a in listapp
                           select new { a.App_zhuang, a.APP_shr, a.APP_liy };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(listapp, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
        public ActionResult Requisition_form(int state = 0, string BB_SQ_xmmc = null, string BB_SQ_khmc = null, string BB_SQ_sqrq = null, string BB_SQ_gjz = null, int id = 0)
        {
            if (state == 1)
            {
                var listapp = FA.find_Contracts2(BB_SQ_xmmc, BB_SQ_khmc, BB_SQ_sqrq, BB_SQ_gjz);
                var temp = from a in listapp
                           select new { a.App_id, a.AP_bian, a.App_Kehu, a.APP_name, a.App_qishi, a.App_JTime, a.App_dizhi, a.APP_Zhong, a.App_mu, a.App_lei, a.App_sho, a.APP_she, a.App_BanB, a.App_bu, a.App_zhuang, a.App_bei, a.AP_ren };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 2)
            {
                Applications applications = db.Applications.Where(x => x.AP_bian == BB_SQ_xmmc).FirstOrDefault();
                db.Applications.Remove(applications);
                int sungko = db.SaveChanges();

                Designdraw designdraw = db.Designdraw.Where(x => x.D_Ton == BB_SQ_xmmc).FirstOrDefault();
                int sungko2 = 0;
                if (designdraw == null)
                {
                    sungko2 = 1;
                }
                else
                {
                    db.Designdraw.Remove(designdraw);
                    sungko2 = db.SaveChanges();
                }
                string messs = "";
                if (sungko2 > 0 && sungko > 0)
                {
                    messs = "删除成功";
                }
                else
                {
                    messs = "删除失败";
                }
                return Content(messs);
            }
            else if (state == 3)
            {
                var app = db.Applications.Where(x => x.App_id == id).ToList();
                var temp = from a in app
                           select new { a.APP_liy, a.APP_shr };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
        public ActionResult DownloadExcel(List<Applications> Designdraws, int state = 0, string excelName = null, int WT_CD = 0, string Employee_path = null)
        {
            if (state == 1)
            {
                //Employee_path = Employee_path.Replace(" ", string.Empty);
                //Employee_path = Employee_path.Substring(0, Employee_path.Length - 1);
                //Employee_path = Employee_path.Substring(1);
                // 创建Excel文件
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                using (ExcelPackage excel = new ExcelPackage())
                {
                    // 添加工作表
                    var worksheet = excel.Workbook.Worksheets.Add("Sheet1");
                    // 写入数据
                    worksheet.Cells[1, 1].Value = "申请单号";
                    worksheet.Cells[1, 2].Value = "项目申请人";
                    worksheet.Cells[1, 3].Value = "项目负责人";
                    worksheet.Cells[1, 4].Value = "客户名称";
                    worksheet.Cells[1, 5].Value = "项目名称";
                    worksheet.Cells[1, 6].Value = "项目价值";
                    worksheet.Cells[1, 7].Value = "发起时间";
                    worksheet.Cells[1, 8].Value = "过期时间";
                    worksheet.Cells[1, 9].Value = "客户地址";
                    worksheet.Cells[1, 10].Value = "终端客户";
                    worksheet.Cells[1, 11].Value = "询价目的";
                    worksheet.Cells[1, 12].Value = "询价类型";
                    worksheet.Cells[1, 13].Value = "付款方式";
                    worksheet.Cells[1, 14].Value = "是否设计";
                    worksheet.Cells[1, 15].Value = "行业大类";
                    worksheet.Cells[1, 16].Value = "行业小类";
                    worksheet.Cells[1, 17].Value = "包装物";
                    worksheet.Cells[1, 18].Value = "客户需求&项目进展";
                    worksheet.Cells[1, 19].Value = "设计信息";
                    worksheet.Cells[1, 20].Value = "设计要求";
                    worksheet.Cells[1, 21].Value = "项目进度";
                    worksheet.Cells[1, 22].Value = "版本号";
                    worksheet.Cells[1, 23].Value = "项目状态";
                    int i = 2;

                    foreach (Applications des in Designdraws)
                    {
                        Designdraw des2 = db.Designdraw.Where(x => x.D_Ton == des.AP_bian).FirstOrDefault();

                        string khxq = "";

                        if (des2 != null)
                        {
                            if (des2.D_PW != null)
                            {
                                khxq += "产品重量:" + des2.D_PW + "\n";
                            }
                            if (des2.D_SI != null)
                            {
                                khxq += "堆叠说明:" + des2.D_SI + "\n";
                            }
                            //if (des2.D_OI != null)
                            //{
                            //    khxq += "其他信息:" + des2.D_OI + "\n";
                            //}
                            if (des2.D_MOF != null)
                            {
                                khxq += "运输方式:" + des2.D_MOF + "\n";
                            }
                            if (des2.D_PT != null)
                            {
                                khxq += "包装类型:" + des2.D_PT + "\n";
                            }
                            if (des2.D_PR != null)
                            {
                                khxq += "防护要求:" + des2.D_PR + "\n";
                            }
                            if (des2.D_OR != null)
                            {
                                khxq += "其他要求:" + des2.D_OR + "\n";
                            }
                            if (des2.D_SR != null)
                            {
                                khxq += "标准要求:" + des2.D_SR + "\n";
                            }
                        }

                        string sub = "";
                        string xmjd = "";
                        string category = "";
                        Applications app = db.Applications.Where(x => x.AP_bian == des.AP_bian).FirstOrDefault();
                        if (app != null)
                        {
                            if (app.App_hangda != null)
                            {
                                int jsjkd = int.Parse(app.App_hangda.ToString());
                                category = db.IndustryCategory.Where(x => x.ic_id == jsjkd).FirstOrDefault().ic_name;
                            }
                            else
                            {
                                category = "N/A";
                            }
                            if (app.App_hangxiao != null)
                            {
                                int widhi = int.Parse(app.App_hangxiao.ToString());
                                if (widhi == 0)
                                {
                                    sub = "N/A";
                                }
                                else
                                {
                                    sub = db.IndustrySubcategory.Where(x => x.isu_id == widhi).FirstOrDefault().isu_name;
                                }
                            }
                            else
                            {
                                sub = "N/A";
                            }
                        }


                        var list = db.BeiZhu.Where(x => x.B_Bian == des.AP_bian).ToList();

                        list = list.OrderByDescending(x => x.B_id).ToList();

                        string bz = "";
                        foreach (BeiZhu b in list)
                        {
                            if (bz == "")
                            {
                                bz = b.B_Date + " " + b.B_BR + ":" + b.B_bei;
                            }
                            else
                            {
                                bz += "\n" + b.B_Date + " " + b.B_BR + ":" + b.B_bei;
                            }
                        }
                        string zt = "";
                        if (app != null)
                        {
                            if (app.App_bu == "1")
                            {
                                xmjd = "报价发起";
                            }
                            if (app.App_bu == "2")
                            {
                                xmjd = "BOM重置";
                            }
                            if (app.App_bu == "3")
                            {
                                xmjd = "工艺配置";
                            }
                            if (app.App_bu == "4")
                            {
                                xmjd = "物料询价";
                            }
                            if (app.App_bu == "5")
                            {
                                xmjd = "物料核价";
                            }
                            if (app.App_bu == "6")
                            {
                                xmjd = "对外报价";
                            }
                            if (app.App_bu == "7")
                            {
                                xmjd = "报价生成";
                            }
                            if (app.App_bu == "-99")
                            {
                                if (app.APP_she == "N")
                                {
                                    xmjd = "设计完成";
                                }
                                else
                                {
                                    xmjd = "询价完成";
                                }

                            }
                        }

                        int index = 1;
                        worksheet.Cells[i, index].Value = app.AP_bian;
                        index++;
                        worksheet.Cells[i, index].Value = app.AP_ren;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_fzr;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_Kehu;
                        worksheet.Cells[i, index].Style.WrapText = true;
                        index++;
                        worksheet.Cells[i, index].Value = app.APP_name;
                        worksheet.Cells[i, index].Style.WrapText = true;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_Jz;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_qishi == null || app.App_qishi == "" ? DateTime.Parse("1999-1-1") : DateTime.Parse(app.App_qishi);
                        worksheet.Cells[i, index].Style.Numberformat.Format = "yyyy/mm/dd";
                        index++;
                        worksheet.Cells[i, index].Value = app.App_JTime == null || app.App_JTime == "" ? DateTime.Parse("1999-1-1") : DateTime.Parse(app.App_JTime);
                        worksheet.Cells[i, index].Style.Numberformat.Format = "yyyy/mm/dd";
                        index++;
                        worksheet.Cells[i, index].Value = app.App_dizhi;
                        worksheet.Cells[i, index].Style.WrapText = true;
                        index++;
                        worksheet.Cells[i, index].Value = app.APP_Zhong;
                        worksheet.Cells[i, index].Style.WrapText = true;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_mu;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_lei;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_sho;
                        index++;
                        worksheet.Cells[i, index].Value = app.APP_she == "S" ? "Y" : app.APP_she;
                        index++;
                        worksheet.Cells[i, index].Value = category;
                        index++;
                        worksheet.Cells[i, index].Value = sub;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_baozhuangwu;
                        index++;
                        worksheet.Cells[i, index].Value = bz;
                        worksheet.Cells[i, index].Style.WrapText = true;
                        index++;
                        worksheet.Cells[i, index].Value = khxq;
                        worksheet.Cells[i, index].Style.WrapText = true;
                        index++;
                        worksheet.Cells[i, index].Value = des2 == null ? "N/A" : des2.D_OI;
                        worksheet.Cells[i, index].Style.WrapText = true;
                        index++;
                        worksheet.Cells[i, index].Value = xmjd;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_BanB;
                        index++;
                        worksheet.Cells[i, index].Value = app.App_xmzt;

                        worksheet.Row(i).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
                        worksheet.Row(i).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;

                        i++;
                    }
                    worksheet.Cells["A:Z"].AutoFitColumns();
                    worksheet.Cells.Style.ShrinkToFit = true;
                    worksheet.Column(19).Width = 40;
                    worksheet.Column(18).Width = 40;
                    worksheet.Column(4).Width = 40;
                    worksheet.Column(5).Width = 40;
                    worksheet.Column(9).Width = 30;
                    worksheet.Column(10).Width = 40;
                    worksheet.Column(17).Width = 40;

                    string path = "";
                    path = Server.MapPath("~/Files/");
                    string Name = excelName + ".xlsx";
                    // 确保目录存在  
                    Directory.CreateDirectory(path);

                    // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                    string fileName = Path.GetFileNameWithoutExtension(Name) + "_" + Guid.NewGuid() + Path.GetExtension(Name);

                    // 保存文件到服务器  
                    string filePath = Path.Combine(path, fileName);
                    excel.SaveAs(filePath);
                    return Json(filePath);
                }

            }
            return View();
        }
        #region 客户批量添加
        public ActionResult Kehupl(HttpPostedFileBase file)
        {
            string path = "";
            try
            {
                if (file != null && file.ContentLength > 0)
                {
                    // 指定保存文件的路径（服务器上的实际路径）  
                    path = Server.MapPath("~/Files/");
                    // 确保目录存在  
                    Directory.CreateDirectory(path);

                    // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                    string fileName = file.FileName;//只保存一个文件 有文件就删除

                    // 保存文件到服务器  
                    string filePath = Path.Combine(path, fileName);
                    file.SaveAs(filePath);//真实路径
                    System.Data.DataTable table = MaterialController.ExcelToDatatables(filePath, "Sheet1", true);


                    //自定义一个datatable
                    var table1 = new System.Data.DataTable();
                    table1.Columns.Add("CL_bian", typeof(string));
                    table1.Columns.Add("CL_name", typeof(string));
                    table1.Columns.Add("CL_huobi", typeof(string));//支付货币
                    //去除空值
                    int sjinag = 0;
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        DataRow dataRow = table.Rows[i];//获取每一行的值
                        var bian = dataRow[0].ToString();
                        var cuzn = db.Clirntele.FirstOrDefault(s => s.CL_bian == bian);
                        if (cuzn == null)
                        {
                            var clis = new Clirntele();
                            clis.CL_bian = bian.ToString();
                            clis.CL_name = dataRow[1].ToString();
                            clis.CL_di = "无";
                            clis.CL_lian = "无";
                            clis.CL_sho = "无";
                            clis.CL_Huobi = dataRow[2].ToString();
                            db.Clirntele.Add(clis);
                        }
                        else
                        {
                            cuzn.CL_bian = bian.ToString();
                            cuzn.CL_name = dataRow[1].ToString();
                            cuzn.CL_Huobi = dataRow[2].ToString();
                            db.Entry(cuzn).State = EntityState.Modified;
                        }
                        sjinag += db.SaveChanges();
                    }

                    string message = sjinag == table.Rows.Count ? "添加成功" : "添加失败";
                    return Content(message);
                }
                else
                {
                    // 返回失败消息  
                    return Json(new { success = false, message = "没有文件被上传或者文件大小为0." });
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion
        public ActionResult Bohuus(Designdraw dsres, string shunnf = "")
        {

            var app = db.Applications.Where(s => s.AP_bian == shunnf).FirstOrDefault();//单据

            var der = db.Designdraw.Where(s => s.D_Ton == shunnf).FirstOrDefault();
            string message = "";
            int num = 0;
            if (der == null)
            {
                message = "1";
                return Content(message);
            }
            if (der != null)
            {
                der.D_zhuang = "3";
                db.Entry(der).State = EntityState.Modified;
                num = db.SaveChanges();
                var beizhu = db.ShejinBeiZhu.Where(s => s.SJ_Bian == shunnf).ToList();
                foreach (var item in beizhu)
                {
                    item.SJ_ZT = "xcsc";
                    db.Entry(item).State = EntityState.Modified;
                    db.SaveChanges();
                }
                var bhcomt = db.BoHUijl.Where(s => s.BH_appbian == shunnf).ToList();
                var cishu = bhcomt.Count() + 1;
                var bh = new BoHUijl()
                {
                    BH_appbian = dsres.D_Ton,
                    BH_ren = dsres.D_dhr,
                    BH_JL = dsres.D_dhly,
                    BH_cishu = cishu,
                };
                db.BoHUijl.Add(bh);
                db.SaveChanges();
                if (num == 1)
                {
                    var shhn = new BeiZhu()
                    {
                        B_Bian = dsres.D_Ton,
                        B_bei = dsres.D_dhly,
                        B_BR = dsres.D_dhr,
                        B_Date = DateTime.Now.ToString("yyyy-M-d")
                    };
                    db.BeiZhu.Add(shhn);
                    db.SaveChanges();
                }
                message = num > 0 ? "2" : "3";
                return Content(message);
            }
            //添加代办
            return View();
        }
        #region 同步客户
        public ActionResult Tongbu(int id = 0)
        {
            var cel = db.Clirntele.Find(id);
            var zhujum = cel.CL_zhu == null ? cel.CL_name.Substring(0, 4) : cel.CL_zhu.ToString();
            var shuoshu = cel.CL_shuo == null ? "苏州工业园区兰多包装工程有限公司" : cel.CL_zhu.ToString();
            //集成查询客户
            var client = new K3CloudApi();
            //用于记录结果
            StringBuilder Info = new StringBuilder();
            //业务对象标识
            string formId = "BD_Customer";
            //添加编码
            string cs = "{\"NeedUpDateFields\": [],\r\n    \"NeedReturnFields\": [],\r\n    \"IsDeleteEntry\": \"true\",\r\n    \"SubSystemId\": \"\",\r\n    \"IsVerifyBaseDataField\": \"false\",\r\n    \"IsEntryBatchFill\": \"true\",\r\n    \"ValidateFlag\": \"true\",\r\n    \"NumberSearch\": \"true\",\r\n    \"IsAutoAdjustField\": \"false\",\r\n    \"InterationFlags\": \"\",\r\n    \"IgnoreInterationFlag\": \"\",\r\n    \"IsControlPrecision\": \"false\",\r\n    \"ValidateRepeatJson\": \"false\",\r\n    \"Model\": {\r\n        \"FCUSTID\": 0,\r\n        \"FCreateOrgId\": {\r\n            \"FNumber\": \"10.01\"\r\n        },\r\n        \"FUseOrgId\": {\r\n            \"FNumber\": \"10.01\"\r\n        },\r\n        \"FName\": \"" + cel.CL_name + "\",\r\n   \"FShortName\": \"" + cel.CL_name + "\",     \"FCOUNTRY\": {\r\n            \"FNumber\": \"China\"\r\n        },\r\n        \"FADDRESS\": \"" + cel.CL_di + "\",\r\n        \"FTEL\": \"" + cel.CL_lian + "\",\r\n        \"FINVOICETITLE\": \"" + cel.CL_name + "\",\r\n        \"FIsGroup\": false,\r\n        \"FIsDefPayer\": false,\r\n        \"FCustTypeId\": {\r\n            \"FNumber\": \"KHLB001_SYS\"\r\n        },\r\n        \"FTRADINGCURRID\": {\r\n            \"FName\": \"" + cel.CL_Huobi + "\"\r\n        },\r\n        \"FTRANSLEADTIME\": 0,\r\n        \"FInvoiceType\": \"1\",\r\n        \"FTaxType\": {\r\n            \"FNumber\": \"SFL02_SYS\"\r\n        },\r\n        \"FPriority\": 1,\r\n        \"FTaxRate\": {\r\n            \"FNumber\": \"SL02_SYS\"\r\n        },\r\n        \"FISCREDITCHECK\": true,\r\n        \"FIsTrade\": true,\r\n        \"FUncheckExpectQty\": false,\r\n        \"F_SMGS_zjm\": \"" + zhujum + "\",\r\n\"F_SMGS_ssfr\":\"" + shuoshu + "\",\r\n        \"F_SMGS_Ggbz\": \"" + cel.CL_bei + "\",\r\n        \"FLegalPerson\": \"" + shuoshu + "\",\r\n        \"FRegisterFund\": \"NA\",\r\n        \"FFoundDate\": \"NA\",\r\n        \"FDomains\": \"NA\",\r\n        \"FRegisterAddress\": \"NA\",        \"FT_BD_CUSTOMEREXT\": {\r\n            \"FEnableSL\": false,\r\n            \"FMarginLevel\": 0.0,\r\n            \"FALLOWJOINZHJ\": false\r\n        }\r\n    }}";
            var resultJson = client.Save(formId, cs);
            var resultJObject = JObject.Parse(resultJson);
            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            var BONID = resultJObject.SelectToken("$.Result.Id");
            var BONNmuber = resultJObject.SelectToken("$.Result.Number");
            var CuoWu = resultJObject.SelectTokens("$..Message");
            var jsongStr = "";
            //判断并记录结果
            bool isSucc = false;
            if (queryNode == null)
            {
                Info.AppendLine("返回异常");
                jsongStr = "提交失败";
            }
            else
            {
                var isSuccess = queryNode.Value<Boolean>();
                if (isSuccess)
                {
                    //提交
                    //读取配置，初始化SDK
                    K3CloudApi clients = new K3CloudApi();
                    //用于记录结果
                    StringBuilder Infoed = new StringBuilder();
                    //业务对象标识
                    string formIdse = "BD_Customer";
                    //请求参数，要求为json字符串
                    string jsonDataws = "{\"CreateOrgId\":0,\"Numbers\":\"" + BONNmuber + "\",\"Ids\":\"" + BONID + "\",\"SelectedPostId\":0,\"UseOrgId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";
                    //调用接口
                    var resultJsonsw = client.Submit(formIdse, jsonDataws);
                    //对返回结果进行解析和校验，这里使用的是JsonPatch
                    var resultJObjectss = JObject.Parse(resultJsonsw);
                    var queryNodes = resultJObjectss.SelectToken("$..IsSuccess");
                    //判断并记录结果
                    if (queryNodes == null)
                    {
                        Infoed.AppendLine("返回异常");
                    }
                    else
                    {
                        isSucc = queryNode.Value<Boolean>();
                        Infoed.AppendLine(isSucc ? "操作成功" : "操作失败");
                    }
                }
                Info.AppendLine(isSuccess ? "操作成功" : "操作失败");
                if (isSucc)
                {
                    jsongStr = "提交成功";

                }
            }
            return Content(jsongStr);
        }
        #endregion
        #region 项目重启

        #endregion
        #region  Bom批量更新物料价格 
        public ActionResult Bom_Plgx(int id = 0)
        {
            if (id == 1)
            {
                /*try
                {*/
                //获取BOM中所有的纸板物料且有工艺记录
                var BOM = db.BOMini.Where(s => s.BOM2_Sone == "1" || s.BOM2_ST == "纸制品" || s.BOM2_ST == "纸质").ToList();
                var bom1 = BOM.Where(s => s.BOM2_bian.Contains("ERP") && s.BOM2_Gong != null && (s.BOM2_ST == "彩印纸箱" || s.BOM2_ST == "水印拉链箱" || s.BOM2_ST == "水印瓦楞箱")).ToList();
                //根据条件获取纸板类型
                foreach (var item in bom1)
                {
                    var St = item.BOM2_ST;
                    var Liaos = item.BOM2_liao;
                    var Bid = item.BOM2_id.ToString();
                    //替换物料价格
                    var OId = item.BOM2_Gong;
                    //获取物料楞型
                    var shun = db.ProcessRecord.FirstOrDefault(s => s.wl_liao == Bid);
                    var Lx = shun.wl_leng;//楞型
                    var Zid = shun.prr_id;
                    //查物料类型
                    var lx = db.CraftMaterials.Where(s => s.prr_id == Zid).ToList();
                    string shu = "";
                    string HSJIN = "";
                    var sj = shun.wl_gui;
                    if (Lx != "N/A")
                    {
                        if (St == "彩印纸箱" || St == "水印拉链箱" || St == "水印瓦楞箱")
                        {
                            if (St == "彩印纸箱")
                            {
                                HSJIN = "彩盒纸板";
                                for (int i = 0; i < lx.Count(); i++)
                                {
                                    var Hj = lx[i].cl_id;
                                    if (Hj != null)
                                    {
                                        var s = db.parice.FirstOrDefault(j => j.PA_ID == Hj).PA_KZ.ToString();//kezhong
                                        if (i != (lx.Count() - 1))
                                        {
                                            shu += s + "*";
                                        }
                                        else
                                        {
                                            shu += s;
                                        }
                                    }

                                }
                            }
                            else if (St == "水印拉链箱" || St == "水印瓦楞箱")
                            {
                                for (int i = 0; i < lx.Count(); i++)
                                {
                                    var Hj = lx[i].cl_id;
                                    if (Hj != null)
                                    {
                                        var s = db.parice.FirstOrDefault(j => j.PA_ID == Hj).PA_KZ.ToString();//kezhong
                                        if (i != (lx.Count() - 1))
                                        {
                                            shu += s + "*";
                                        }
                                        else
                                        {
                                            shu += s;
                                        }
                                    }
                                }
                            }
                            //获取物料的价格 调用方法
                            List<List<object>> result = MaterialController.NewMethod(shu, Lx, HSJIN);
                            var dany = result.Count == 0 ? null : result[0];
                            if (dany != null)
                            {
                                //获取价格
                                List<double> doubles = new List<double>();
                                for (int i = 0; i < result.Count; i++)
                                {
                                    doubles.Add(double.Parse(dany[1].ToString()));
                                }
                                var jia = doubles.Min();//纸板价格(最小)
                                double mianj = 1;
                                if (sj != null)
                                {
                                    mianj = Mianji(sj, mianj);
                                    mianj = mianj / 1000000;
                                }
                                var jiage = double.Parse(jia.ToString()) * mianj;//纸板价格
                                var OP = db.operational.Where(s => s.OP_ID == OId).FirstOrDefault();//工艺价格记录行
                                var JINML = db.Formation.Where(s => s.FM_bai == Liaos).FirstOrDefault();//工艺价格记录行

                                //更改价格记录
                                if (OP != null)
                                {
                                    var A = OP.OP_YUN == null ? 0 : double.Parse(OP.OP_YUN.ToString());
                                    var B = OP.OP_JIA == null ? 0 : double.Parse(OP.OP_JIA.ToString());
                                    var D = OP.OP_GUAN == null ? 0 : double.Parse(OP.OP_GUAN.ToString());
                                    var Priic = A + B + jiage + D;
                                    OP.OP_CAi = (decimal?)jiage;
                                    OP.OP_price = (decimal?)Priic;
                                    db.Entry(OP).State = EntityState.Modified;
                                    db.SaveChanges();
                                    if (JINML != null)
                                    {
                                        JINML.FM_price = (decimal?)Priic;
                                        db.Entry(JINML).State = EntityState.Modified;
                                        db.SaveChanges();
                                    }
                                }
                            }
                        }

                    }
                }
                return Content("物料已更新");
                /* }
                 catch (Exception ex)
                 {
                     string msg = ex.Message;
                     return Content(msg);
                 }*/
            }
            return View();
        }

        private static double Mianji(string sj, double mianj)
        {
            var k = sj.Split('*');
            double rest;
            foreach (var s in k)
            {
                if (!double.TryParse(s, out rest))
                {
                    rest = 0.0;
                }
                else
                {
                    rest = double.Parse(s);
                }
                mianj *= rest;
            }

            return mianj;
        }

        private void Hjngm(string St, List<CraftMaterials> lx, ref string shu, ref string HSJIN)
        {
            if (St == "彩印纸箱")
            {
                HSJIN = "彩盒纸板";
                for (int i = 1; i < lx.Count(); i++)
                {
                    var Hj = lx[i].cl_id;
                    var s = db.parice.FirstOrDefault(j => j.PA_ID == Hj).PA_KZ.ToString();//kezhong
                    if (i != (lx.Count() - 1))
                    {
                        shu += s + "*";
                    }
                    else
                    {
                        shu += s;
                    }
                }
            }
            else if (St == "水印拉链箱" || St == "水印瓦楞箱")
            {
                foreach (var d in lx)
                {
                    var Hj = d.cl_id;
                    var s = db.parice.FirstOrDefault(j => j.PA_ID == Hj).PA_KZ.ToString();//kezhong
                    if (d.Equals(lx))
                    {
                        shu += s + "*";
                    }
                    else
                    {
                        shu += s;
                    }
                }
            }
        }
        #endregion


        #region CopyBOMhang
        public ActionResult BOMCopyH(List<Formation> formation)
        {
            if (true)
            {
                int sun = 0;
                var shu = new List<Formation>();
                foreach (var item in formation)
                {
                    var ID = item.FM_bai;
                    //查询物料并复制保存
                    var FromEd = db.Formation.FirstOrDefault(s => s.FM_bai == ID);

                    //更改物料编码
                    var bain = db.Formation.ToList();
                    var Binss = "WL" + bain[bain.Count() - 1].FM_ID;
                    var F = new Formation()
                    {
                        FM_bai = Binss,
                        FM_name = FromEd.FM_name,
                        MA_ID = FromEd.MA_ID,
                        FM_long = FromEd.FM_long,
                        FM_kuan = FromEd.FM_kuan,
                        FM_gao = FromEd.FM_gao,
                        FM_price = FromEd.FM_price,
                        PR_ID = FromEd.PR_ID,
                        FM_ji = FromEd.FM_ji,
                        FM_Zhuang = FromEd.FM_Zhuang,
                        FM_kong = FromEd.FM_kong,
                        FM_gg = FromEd.FM_gg,
                        FM_nyl = FromEd.FM_nyl,
                        FM_yj = FromEd.FM_yj,
                        FM_bmcl = FromEd.FM_bmcl,
                        FM_ycl = FromEd.FM_ycl,
                        FM_ms = FromEd.FM_ms,
                        FM_zx = FromEd.FM_zx,
                        FM_ej = FromEd.FM_ej,
                        FM_Jieti = FromEd.FM_Jieti,
                        ERP_id = FromEd.ERP_id,
                    };
                    db.Formation.Add(F);
                    db.SaveChanges();
                    shu.Add(F);
                }
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(shu, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
        #endregion

        #region 图纸文件
        public ActionResult TuZExcel(string bian = "")
        {
            var Appian = db.Applications.Where(s => s.AP_bian == bian).ToList();
            if (Appian == null)
            {
                return Json("N");
            }
            else
            {
                var shun = db.Design.Where(s => s.DE_shen == bian).ToList();
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                using (ExcelPackage excel = new ExcelPackage())
                {
                    // 添加工作表
                    var worksheet = excel.Workbook.Worksheets.Add("Sheet1");
                    // 写入数据
                    worksheet.Cells[1, 1].Value = "文件名";
                    worksheet.Cells[1, 2].Value = "物料编码";
                    worksheet.Cells[1, 3].Value = "物料名称";
                    worksheet.Cells[1, 4].Value = "行业大类";
                    worksheet.Cells[1, 5].Value = "行业小类";
                    worksheet.Cells[1, 6].Value = "包装品类";
                    worksheet.Cells[1, 7].Value = "图纸类别";
                    worksheet.Cells[1, 8].Value = "包装物名称";
                    worksheet.Cells[1, 9].Value = "版本";
                    worksheet.Cells[1, 10].Value = "上传人";
                    worksheet.Cells[1, 11].Value = "设计用时";
                    worksheet.Cells[1, 12].Value = "审核状态";
                    worksheet.Cells[1, 13].Value = "审核时间";
                    worksheet.Cells[1, 14].Value = "审核说明";
                    worksheet.Cells[1, 15].Value = "上传时间";
                    int i = 2;

                    foreach (var des in shun)
                    {
                        var index = 1;
                        worksheet.Cells[i, index].Value = des.DE_TZname;
                        index++;
                        worksheet.Cells[i, index].Value = des.bom_id; index++;
                        var BOiji = db.BOMini.Where(s => s.BOM2_liao == des.bom_id).FirstOrDefault();
                        worksheet.Cells[i, index].Value = BOiji == null ? "" : BOiji.BOM2_wuLiu; index++;
                        worksheet.Cells[i, index].Value = des.IndustryCategory == null ? "" : des.IndustryCategory.ic_name; index++;
                        worksheet.Cells[i, index].Value = des.IndustrySubcategory == null ? "" : des.IndustrySubcategory.isu_name; index++;
                        worksheet.Cells[i, index].Value = des.DE_bzpl; index++;
                        worksheet.Cells[i, index].Value = des.DE_bzw; index++;
                        worksheet.Cells[i, index].Value = des.DE_BB; index++;
                        worksheet.Cells[i, index].Value = des.De_ren; index++;
                        worksheet.Cells[i, index].Value = des.DE_Slong; index++;
                        worksheet.Cells[i, index].Value = des.DE_tuiLei; index++;
                        worksheet.Cells[i, index].Value = des.DZ_ShTIme; index++;
                        worksheet.Cells[i, index].Value = des.DZ_Fnajm; index++;
                        worksheet.Cells[i, index].Value = des.De_shijian;
                        worksheet.Row(i).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
                        worksheet.Row(i).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        i++;
                    }
                    worksheet.Cells["A:Z"].AutoFitColumns();
                    worksheet.Cells.Style.ShrinkToFit = true;
                    string path = "";
                    path = Server.MapPath("~/Files/");
                    string Name = "图纸下载文件.xlsx";
                    // 确保目录存在  
                    Directory.CreateDirectory(path);

                    // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                    string fileName = Path.GetFileNameWithoutExtension(Name) + "_" + Guid.NewGuid() + Path.GetExtension(Name);

                    // 保存文件到服务器  
                    string filePath = Path.Combine(path, fileName);
                    excel.SaveAs(filePath);
                    return Json(filePath);
                }

            }
            return View();
        }
        #endregion

        #region 批量下载文件
        public ActionResult TuZPLExcel(List<Applications> application, string ades = "")
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            using (ExcelPackage excel = new ExcelPackage())
            {
                // 添加工作表
                var worksheet = excel.Workbook.Worksheets.Add("Sheet1");
                // 写入数据
                worksheet.Cells[1, 1].Value = "文件名";
                worksheet.Cells[1, 2].Value = "物料编码";
                worksheet.Cells[1, 3].Value = "物料名称";
                worksheet.Cells[1, 4].Value = "行业大类";
                worksheet.Cells[1, 5].Value = "行业小类";
                worksheet.Cells[1, 6].Value = "包装品类";
                worksheet.Cells[1, 7].Value = "图纸类别";
                worksheet.Cells[1, 8].Value = "包装物名称";
                worksheet.Cells[1, 9].Value = "版本";
                worksheet.Cells[1, 10].Value = "上传人";
                worksheet.Cells[1, 11].Value = "设计用时";
                worksheet.Cells[1, 12].Value = "审核状态";
                worksheet.Cells[1, 13].Value = "审核时间";
                worksheet.Cells[1, 14].Value = "审核说明";
                worksheet.Cells[1, 15].Value = "上传时间";
                int i = 2;
                List<Applications> app = new List<Applications>();
                for (int j = 0; j < application.Count(); j++)
                {
                    for (int k = 0; k < application.Count(); k++)
                    {
                        if (j != k && application[j].AP_bian == application[k].AP_bian)
                        {
                            application.Remove(application[j]);
                        }
                    }
                }
                foreach (Applications dessa in application)
                {
                    var Shun = db.Design.Where(s => s.DE_shen == dessa.AP_bian && s.DE_lei == "图纸").ToList();
                    foreach (var des in Shun)
                    {
                        var index = 1;
                        worksheet.Cells[i, index].Value = des.DE_TZname;
                        index++;
                        worksheet.Cells[i, index].Value = des.bom_id; index++;
                        var BOiji = db.BOMini.Where(s => s.BOM2_liao == des.bom_id).FirstOrDefault();
                        worksheet.Cells[i, index].Value = BOiji == null ? "" : BOiji.BOM2_wuLiu; index++;
                        worksheet.Cells[i, index].Value = des.IndustryCategory == null ? "" : des.IndustryCategory.ic_name; index++;
                        worksheet.Cells[i, index].Value = des.IndustrySubcategory == null ? "" : des.IndustrySubcategory.isu_name; index++;
                        worksheet.Cells[i, index].Value = des.DE_bzpl; index++;
                        worksheet.Cells[i, index].Value = des.DE_bzw; index++;
                        worksheet.Cells[i, index].Value = des.DE_BB; index++;
                        worksheet.Cells[i, index].Value = des.De_ren; index++;
                        worksheet.Cells[i, index].Value = des.DE_Slong; index++;
                        worksheet.Cells[i, index].Value = des.DE_tuiLei; index++;
                        worksheet.Cells[i, index].Value = des.DZ_ShTIme; index++;
                        worksheet.Cells[i, index].Value = des.DZ_Fnajm; index++;
                        worksheet.Cells[i, index].Value = des.De_shijian == null || des.De_shijian == "" ? DateTime.Parse("1890-10-1") : DateTime.Parse(des.De_shijian);
                        worksheet.Row(i).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
                        worksheet.Row(i).Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        i++;
                    }
                }

                worksheet.Cells["A:Z"].AutoFitColumns();
                worksheet.Cells.Style.ShrinkToFit = true;
                worksheet.Column(15).Style.Numberformat.Format = "yyyy/mm/dd";
                string path = "";
                path = Server.MapPath("~/Files/");
                string Name = ades + ".xlsx";
                // 确保目录存在  
                Directory.CreateDirectory(path);

                // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                string fileName = Path.GetFileNameWithoutExtension(Name) + "_" + Guid.NewGuid() + Path.GetExtension(Name);

                // 保存文件到服务器  
                string filePath = Path.Combine(path, fileName);
                excel.SaveAs(filePath);
                return Json(filePath);
            }
            return View();
        }
        #endregion

        #region 手动版本变更
        public ActionResult VersionC(string bian = "", string ING = "", int state = 0)
        {
            ///变更循序：1、复制表头行 并修改单据号
            ///2、复制物料
            ///3、复制设计
            ///4、
            var App = db.Applications.Where(s => s.AP_bian == bian).FirstOrDefault();
            if (App != null)
            {
                if (state == 1)
                {
                    var SJbia = "";
                    var shunf = "";
                    var BianSp = App.AP_bian.Split('_');
                    if (BianSp.Length > 1)
                    {
                        SJbia = BianSp[0] + "_" + App.App_BanB;
                    }
                    else
                    {
                        SJbia = App.AP_bian + "_" + App.App_BanB;
                    }
                    //更改单据号
                    var JBIG = int.Parse(App.App_BanB) + 1;
                    var HUNF = "保存";
                    var shuj = shoTJ.BGAPP(App, SJbia, JBIG, HUNF);
                    db.Applications.Add(shuj);
                    var HNG = db.SaveChanges();
                    if (HNG > 0)
                    {
                        //复制物料并修改
                        var FZOBM = db.BOMini.Where(s => s.BOM2_bian == bian).ToList();
                        foreach (var f in FZOBM)
                        {
                            var BOMi = shoTJ.BO(f, SJbia, JBIG);
                            db.BOMini.Add(BOMi);
                        }
                        var B = db.SaveChanges();
                        //复制设计并修改
                        var FZDER = db.Designdraw.Where(s => s.D_Ton == bian).FirstOrDefault();
                        var BZ = "5";
                        var DERS = shoTJ.Des(FZDER, SJbia, JBIG, BZ);
                        db.Designdraw.Add(DERS);
                        var C = db.SaveChanges();
                        shunf = B == 1 && C == 1 ? "变更成功" : "变更失败";
                        if (shunf == "变更成功")
                        {
                            //失效当前单据  1--失效
                            App.AP_BGYY = ING;
                            App.AP_QTJY = "1";
                            db.Entry(App).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }
                    else
                    {
                        shunf = "变更失败";
                    }
                    return Json(shunf);
                }
                if (state == 2)
                {
                    var SJbia = "";
                    var shunf = "";
                    var BianSp = App.AP_bian.Split('_');
                    if (BianSp.Length > 1)
                    {
                        SJbia = BianSp[0] + "_" + App.App_BanB;
                    }
                    else
                    {
                        SJbia = App.AP_bian + "_" + App.App_BanB;
                    }
                    //更改单据号
                    var JBIG = int.Parse(App.App_BanB) + 1;
                    var HUNF = "提交";
                    var shuj = shoTJ.BGAPP(App, SJbia, JBIG, HUNF);
                    db.Applications.Add(shuj);
                    var HNG = db.SaveChanges();
                    if (HNG > 0)
                    {
                        //复制物料并修改
                        var FZOBM = db.BOMini.Where(s => s.BOM2_bian == bian).ToList();
                        foreach (var f in FZOBM)
                        {
                            var BOMi = shoTJ.BO(f, SJbia, JBIG);
                            db.BOMini.Add(BOMi);
                        }
                        var B = db.SaveChanges();
                        //复制设计并修改
                        var FZDER = db.Designdraw.Where(s => s.D_Ton == bian).FirstOrDefault();
                        var BZ = "5";
                        var DERS = shoTJ.Des(FZDER, SJbia, JBIG, BZ);
                        db.Designdraw.Add(DERS);
                        var C = db.SaveChanges();
                        shunf = B == 1 && C == 1 ? "变更成功" : "变更失败";
                        if (shunf == "变更成功")
                        {
                            //失效当前单据  1--失效
                            App.AP_BGYY = ING;
                            App.AP_QTJY = "1";
                            db.Entry(App).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }
                    else
                    {
                        shunf = "变更失败";
                    }
                    return Json(shunf);
                }
            }
            return View();
        }
        #endregion

        #region 校验文件报表
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="name">名称</param>
        /// <param name="shen">版本</param>
        /// <param name="DE_BB"></param>
        /// <returns></returns>
        public ActionResult FileVerison(string fileName, string name, string shen, string DE_BB)
        {
            var cunzai = db.Design.Where(s => s.DE_TZname == fileName && DE_BB == DE_BB).FirstOrDefault();
            var shun = cunzai == null ? true : false;
            return Json(shun);
        }
        public ActionResult FileVerison1(string WL, string BM,int name)
        {
            var cunzai = db.ShejinBeiZhu.Where(s => s.SJ_Bian == BM && s.SJR_id== name).FirstOrDefault();
            var shun = cunzai == null ? "0" : cunzai.SJ_QTY.ToString();
            return Json(shun);
        }
        #endregion

        #region 老料号新报价
        public ActionResult OldPrice(string bian)
        {
            var Abian = "SQ" + DateTime.Now.ToString("yyyyMMddHHmmss");
            string Times = DateTime.Now.ToString("yyyy-MM-dd");
            try
            {
                var cunzai = db.Applications.Where(s => s.AP_bian == bian).FirstOrDefault();
                if (cunzai != null)
                {
                    //复制更改单据
                    cunzai.AP_bian = Abian;
                    cunzai.App_qishi = Times;
                    cunzai.App_BanB = "1";
                    var bb = cunzai.App_BanB;
                    db.Applications.Add(cunzai);
                    db.SaveChanges();
                    //设计+图纸
                    var Shj = db.Designdraw.Where(s => s.D_Ton == bian).FirstOrDefault();
                    if (Shj != null)
                    {
                        Shj.D_Ton = Abian;
                        Shj.D_Applic = Times;
                        db.Designdraw.Add(Shj);
                        db.SaveChanges();
                    }

                    //--图纸
                    var tu = db.Design.Where(s => s.DE_shen == bian).ToList();
                    foreach (var t in tu)
                    {
                        t.DE_shen = Abian;
                        db.Design.Add(t);
                    }
                    db.SaveChanges();
                    //--备注
                    var Bei = db.BeiZhu.Where(s => s.B_Bian == bian).ToList();
                    foreach (var item in Bei)
                    {
                        item.B_Bian = Abian;
                        db.BeiZhu.Add(item);
                    }
                    db.SaveChanges();
                    //物料
                    var cunzai1 = db.BOMini.Where(s => s.BOM2_bian == bian && s.BOM2_Zhuang == bb).ToList();
                    foreach (var c in cunzai1)
                    {
                        c.BOM2_bian = Abian;
                        var JIu = c.BOM2_id;
                        //复制物料工艺记录
                        var gong = c.BOM2_Gong;
                        var shn = db.operational.Where(s => s.OP_ID == gong).FirstOrDefault();
                        if (shn != null)
                        {
                            db.operational.Add(shn);
                            db.SaveChanges();
                            c.BOM2_Gong = shn.OP_ID;
                        }
                        db.BOMini.Add(c);
                        var wlid = c.BOM2_id;
                        //复制物料记录
                        var pfl = db.ProcessRecord.Where(s => s.wl_liao == JIu.ToString()).FirstOrDefault();
                        var pflid = 0;
                        if (pfl != null)
                        {
                            db.ProcessRecord.Add(pfl);
                            db.SaveChanges();
                            pflid = pfl.prr_id;
                        }
                        if (pflid == 0)
                        {
                            var pfl1 = db.ProcessFlow.Where(s => s.prr_id == pflid).ToList();
                            foreach (var item in pfl1)
                            {
                                item.prr_id = pflid;
                                db.ProcessFlow.Add(item);
                            }
                            db.SaveChanges();
                            var pfl2 = db.CraftMaterials.Where(s => s.prr_id == pflid).ToList();
                            foreach (var item in pfl2)
                            {
                                item.prr_id = pflid;
                                db.CraftMaterials.Add(item);
                            }
                            db.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Abian = ex.Message;
            }

            return Json(Abian);
        }
        #endregion

        #region 过滤报价单模版
        public ActionResult GetBaoJia(string bian, string type,int state=0)
        {
            if (state==1)
            {
                var Jl = db.Sheji.Where(s => s.SJ_gs==bian|| s.SJ_Zhua == "通用").ToList();
                var list = from a in Jl
                           select new
                           {
                               a.SJ_gs,
                               a.SJ_Zhua,
                               a.SJ_Dizhi,
                               a.SJ_beizhu,
                               WNm = a.SJ_Dizhi.Split('/')?[2].Split('_')?[0],
                           };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }
        #endregion
    }

}